package com.chinastock.convertor;

import com.chinastock.Constant;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.pattern.ConverterKeys;
import org.apache.logging.log4j.core.pattern.NamePatternConverter;
import org.apache.logging.log4j.core.pattern.PatternConverter;
import org.apache.logging.log4j.util.PerformanceSensitive;


/**
 * 新建一个PatternLayout的Converter,添加traceId的输出
 * 使用%traceId输出traceId
 * 1、必须将category的属性指定成PatternConverter
 * 2、必须包含一个@ConverterKeys注解，以便可以使用%tid进行选择输出
 *
 * @author wangzhendong
 */
@Plugin(name = "TidPatternConverter", category = PatternConverter.CATEGORY)
@ConverterKeys({Constant.TRACE_ID})
@PerformanceSensitive("allocation")
public final class TraceIdConverter extends NamePatternConverter {
    /**
     * 使用单例模式
     */
    private static final TraceIdConverter INSTANCE =
            new TraceIdConverter(null);

    /**
     * Constructor. 构造函数
     *
     * @param options options, may be null, first element will be interpreted as an abbreviation pattern.
     */
    private TraceIdConverter(final String[] options) {
        super("traceId", "traceId", options);
    }

    /**
     * 3、内部必须有一个newInstance
     *
     * @param options 构建converter的可选参数
     * @return 可选参数
     */
    public static TraceIdConverter newInstance(final String[] options) {
        if (options == null || options.length == 0) {
            return INSTANCE;
        }
        return new TraceIdConverter(options);
    }

    @Override
    public void format(LogEvent event, StringBuilder toAppendTo) {
        try {
            String traceId = event.getContextData().toMap().get(Constant.TRACE_ID);
            if (StringUtils.isBlank(traceId)) {
                traceId = Constant.DEFAULT_NULL;
            }
            toAppendTo.append(traceId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
